package com.yzw.mybatisutils.uitls;

import freemarker.template.Configuration;
import freemarker.template.Template;
import org.apache.log4j.Logger;

import java.io.BufferedWriter;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.nio.charset.StandardCharsets;
import java.util.Map;

/**
 * @author：yzw
 * @Date：2017/11/29
 * @描述：
 */
public class FreemarkerUtil {

	private static final Logger LOGGER = Logger.getLogger(FreemarkerUtil.class);

	private static Template getTemplate(String templateName) {
		try {
			Configuration conf = new Configuration();
			conf.setDefaultEncoding("UTF-8");
			conf.setClassForTemplateLoading(FreemarkerUtil.class, "/templates/mybatis");
			return conf.getTemplate(templateName);
		} catch (Exception e) {
			LOGGER.error(e);
		}
		return null;
	}

	public static boolean writeTemplate(String templateName, Map<String, Object> params, String outFilePath) {
		BufferedWriter writer = null;
		try {
			writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFilePath), StandardCharsets.UTF_8));
			Template template = getTemplate(templateName);
			if (template != null) {
				template.process(params, writer);
				return true;
			}
		} catch (Exception e) {
			LOGGER.error(e);
		} finally {
			if (writer != null) {
				try {
					writer.close();
				} catch (IOException e) {
					LOGGER.error(e);
				}
			}
		}
		return false;
	}
}
